import http from './http'

// 注册请求参数
export interface RegisterRequest {
  username: string
  email: string
  password: string
  captchaKey: string
  captchaCode: string
}

// 登录请求参数
export interface LoginRequest {
  username: string
  password: string
  captchaKey: string
  captchaCode: string
}

// 登录响应
export interface LoginResponse {
  accessToken: string
  refreshToken: string
}

// 刷新token请求
export interface RefreshRequest {
  refreshToken: string
}

// 刷新token响应
export interface RefreshResponse {
  accessToken: string
}

// 认证相关API
export const authApi = {
  // 注册
  register(data: RegisterRequest): Promise<LoginResponse> {
    return http.post('/v1/auth/register', data)
  },

  // 登录
  login(data: LoginRequest): Promise<LoginResponse> {
    return http.post('/v1/auth/login', data)
  },

  // 刷新token
  refresh(data: RefreshRequest): Promise<RefreshResponse> {
    return http.post('/v1/auth/refresh', data)
  },

  // 获取当前用户信息
  me(): Promise<any> {
    return http.get('/v1/auth/me')
  },

  // 健康检查
  health(): Promise<{ ok: boolean }> {
    return http.get('/v1/health')
  },

  // 更新个人资料
  updateProfile(data: UpdateProfileRequest): Promise<any> {
    return http.put('/v1/auth/profile', data)
  },

  // 修改密码
  changePassword(data: ChangePasswordRequest): Promise<void> {
    return http.put('/v1/auth/password', data)
  },

  // 上传头像
  uploadAvatar(file: File): Promise<{ url: string }> {
    const formData = new FormData()
    formData.append('file', file)
    return http.post('/v1/upload/avatar', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  }
}

// 更新个人资料请求
export interface UpdateProfileRequest {
  nickname?: string
  avatarUrl?: string
  bio?: string
  phone?: string
}

// 修改密码请求
export interface ChangePasswordRequest {
  currentPassword: string
  newPassword: string
}

// 验证码相关API
export const captchaApi = {
  // 获取验证码key
  getKey(): Promise<{ key: string }> {
    return http.get('/v1/captcha/key')
  },
  
  // 获取验证码图片
  getImage(key: string): Promise<{ image: string }> {
    return http.get(`/v1/captcha/image/${key}`)
  },
  
  // 验证验证码
  validate(key: string, code: string): Promise<{ valid: boolean; message: string }> {
    return http.post('/v1/captcha/validate', null, {
      params: { key, code }
    })
  }
}
